import React, { Component } from 'react'
import { Card, message, Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { UploadChangeParam, UploadFile } from 'antd/lib/upload/interface';
import './BannerChange.less'
import { baseURL, getRes } from '../../../../../configFile';
import { bannerReq } from '../../../../../requests/Frame'

function getBase64(img: Blob | undefined, callback: (imageUrl: string | ArrayBuffer | null) => void) {
    const reader = new FileReader();
    //先绑定侦听器
    reader.addEventListener('load', () => callback(reader.result));
    if (!!img) {    //是图片便读取
        reader.readAsDataURL(img);      //操作完成时触发事件
    }
}

//检查用户上传的图片格式和大小
function beforeUpload(file: { type: string; size: number; }) {

    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //     message.error('Image must smaller than 2MB!');
    // }
    // return isJpgOrPng && isLt2M;
    return isJpgOrPng;
}

interface IState {
    imageUrl: string | ArrayBuffer | null | undefined,
    loading: boolean
}

export default class BannerChange extends Component<null, IState> {
    state = {
        imageUrl: undefined,
        loading: false
    };
    async componentDidMount() {
        const res = getRes(await bannerReq())
        this.setState({
            ...this.state,
            imageUrl: res.data
        })
    }

    handleChange: ((info: UploadChangeParam<UploadFile<any>>) => void) = info => {

        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done' && info.file.response.isSuccessful === true) {
            getBase64(info.file.originFileObj, imageUrl => {
                window.location.reload()    //刷新页面
                message.success('更换成功')
            }
            );
        }
        else {
            this.setState({
                ...this.state,
                loading: false
            })
            message.error('上传错误')
        }
    };

    render() {
        const uploadButton = (
            <div>
                {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const { imageUrl } = this.state;
        return (
            <Card title="更换头部banner (1280px*71px)" bordered={false} style={{ width: '100%' }}>

                <Upload
                    name="BannerPicture"
                    listType="picture-card"
                    className="banner-uploader"
                    showUploadList={false}
                    action={`${baseURL}/modifyBannerPicture`}
                    beforeUpload={beforeUpload}
                    onChange={this.handleChange}
                    accept={"image/*"}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>

            </Card>
        );
    }
}
